/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.pixlib.sfe.view.dialog 
{
	import net.pixlib.core.PixlibApplication;
	import net.pixlib.plugin.Plugin;
	import net.pixlib.sfe.log.Debug;
	import net.pixlib.sfe.structure.FontFormat;
	import net.pixlib.sfe.util.getTranslation;
	import net.pixlib.sfe.view.ViewList;
	import net.pixlib.sfe.view.abstract.JFrameView;
	import net.pixlib.tms.LocalManager;
	import net.pixlib.tms.LocalManagerEvent;

	import org.aswing.BorderLayout;
	import org.aswing.Insets;
	import org.aswing.JComboBox;
	import org.aswing.JFrame;
	import org.aswing.JOptionPane;
	import org.aswing.JPanel;
	import org.aswing.JScrollPane;
	import org.aswing.JTextArea;
	import org.aswing.border.EmptyBorder;
	import org.aswing.event.FrameEvent;

	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.DropShadowFilter;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.text.Font;
	import flash.utils.ByteArray;

	/**
	 * 'Preview' dialog view.
	 * 
	 * @author Romain Ecarnot
	 */
	public class PreviewLibView extends JFrameView
	{

		//--------------------------------------------------------------------
		// Private properties
		//--------------------------------------------------------------------
		
		/** @private */
		private var _styleListLabels : Array; 

		/** @private */
		private var _styleListFormat : Array; 

		/** @private */
		private var _labelList : JComboBox; 

		/** @private */
		private var _inputArea : JTextArea; 

		/** @private */
		private var _loader : Loader; 

		
		//--------------------------------------------------------------------
		// Public API
		//--------------------------------------------------------------------
		
		/**
		 * Creates view instance.
		 */		
		public function PreviewLibView(owner : Plugin)
		{
			super(owner, ViewList.PREVIEW_VIEW, new JFrame(PixlibApplication.getInstance().root, "Test library", true));
		}

		/**
		 *
		 */
		public function open(libPath : String, formats : Vector.<FontFormat>) : void
		{
			_styleListFormat = [];
			_styleListLabels = [];
			
			_inputArea.setText("");
			
			var len : uint = formats.length;
			var format : FontFormat;
			for(var i : uint = 0;i < len; i++)
			{
				format = formats[i];
				_styleListFormat.push(format.font);
				_styleListLabels.push(format.label);
			}
			
			_labelList.setListData(_styleListLabels);
			
			var file : File = new File(libPath);
			
			var fileStream : FileStream = new FileStream();
			fileStream.open(file, FileMode.READ);
			
			var bytes : ByteArray = new ByteArray();
			fileStream.readBytes(bytes);
			fileStream.close();
			
			_startLoader(bytes);
		}

		/**
		 * Overrides View#show() method to deal with JFrame component.
		 */
		override public function show() : void
		{
			getFrame().setX(PixlibApplication.getInstance().size.width * 0.5 - getFrame().width * 0.5);			getFrame().setY(PixlibApplication.getInstance().size.height * 0.5 - getFrame().height * 0.5);
			getFrame().show();
			
			super.show();
		}

		
		//--------------------------------------------------------------------
		// Protected methods
		//--------------------------------------------------------------------

		/**
		 * Inits User Interface.
		 */
		override protected function onInitView( ) : void
		{
			LocalManager.getInstance().addEventListener(LocalManagerEvent.onLocalChangeEVENT, _onLocalChangeHandler);
			
			getFrame().setContentPane(new JPanel(new BorderLayout(5, 5)));
			getFrame().setResizable(false);
			getFrame().filters = [new DropShadowFilter(0, 0, 0x000000, 0.75, 10, 10, 1, BitmapFilterQuality.MEDIUM)];
			getFrame().setSizeWH(300, 250);
			getFrame().addEventListener(FrameEvent.FRAME_CLOSING, _onCloseFrameHandler);
			
			_styleListFormat = [];
			_styleListLabels = [];
			
			_labelList = new JComboBox(_styleListLabels);
			_labelList.addSelectionListener(_onChangeFormatHandler);
			
			_inputArea = new JTextArea("");
			
			getPanel().setBorder(new EmptyBorder(null, new Insets(5, 5, 5, 5)));
			getPanel().append(_labelList, BorderLayout.NORTH);			getPanel().append(new JScrollPane(_inputArea), BorderLayout.CENTER);
			
			_onLocalChangeHandler();
			
			super.onInitView();
		}

		
		//--------------------------------------------------------------------
		// Private methods
		//--------------------------------------------------------------------
		
		/** @private */
		private function _onLocalChangeHandler(event : LocalManagerEvent = null) : void
		{
			getFrame().setTitle(getTranslation("previewDialogTitle"));
		}
		
		private function _startLoader(bytes : ByteArray) : void 
		{
			var loaderContext : LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
			loaderContext.allowLoadBytesCodeExecution = true;
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.INIT, _onLibLoadedHandler);			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, _onLibErrorHandler);
			_loader.loadBytes(bytes, loaderContext);
		}
		
		private function _releaseLoader() : void 
		{
			_loader.contentLoaderInfo.removeEventListener(Event.INIT, _onLibLoadedHandler);
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, _onLibErrorHandler);
			_loader.unload();
			_loader = null;
		}

		/**
		 * 
		 */
		private function _onLibErrorHandler(event : Event) : void
		{
			Debug.ERROR("Shared Library is not loaded", this);
			
			JOptionPane.showMessageDialog(getTranslation("error"), getTranslation("previewLibError"), null, null, true, null, JOptionPane.OK);
			
			getFrame().dispose();
			
			_releaseLoader();
		}
		
		/**
		 * 
		 */
		private function _onLibLoadedHandler(event : Event) : void
		{
			Debug.DEBUG("Shared library is loaded", this);
			Debug.DEBUG("Embded font " + Font.enumerateFonts(false), this);
			
			_labelList.setSelectedIndex(0);
			_onChangeFormatHandler();
			
			show();
		}
		
		/** @private */
		private function _onChangeFormatHandler(event : Event = null) : void
		{
			var index : int = _labelList.getSelectedIndex();
			
			_inputArea.setFont(_styleListFormat[index]);
			_inputArea.repaintAndRevalidate();
		}
		
		/** @private */
		private function _onCloseFrameHandler(event : Event) : void
		{
			if(_loader) _releaseLoader();
			
			getFrame().dispose();
		}
	}
}
